package reader;

import static utils.NewsEventSystemUtils.getDomains;

import newsEditor.AddedSubtopicEvent;
import newsEditor.ReadEvent;
import newsEventSystem.Console;
import newsEventSystem.News;
import event.Event;
import event.EventService;
import event.InvalidEventTypeException;
import event.Publisher;
import event.Subscriber;

public class Reader extends Thread implements Subscriber, Publisher {

	private static EventService eventService = EventService.getInstance();
	private Console console = new Console("Reader");

	private String getMenuText() {
		String menuText = "1.Subscribe for domains modifications\n"
				+ "2.Subscribe for news\n" + "3.Exit";
		return menuText;
	}

	public void run() {
		console.writeLine("Welcome, reader!");
		console.writeLine("The list of topics is:");
		console.writeLine(getDomains());
		console.writeLine(getMenuText());
		int option = 0;
		do {
			console.writeLine("\nPlease insert your option:");
			try {
				String line = console.readLine();
				if (line == null) {
					option = 3;
				} else {
					option = Integer.parseInt(line.trim());
				}
				switch (option) {
				case 1:
					try {
						eventService.subscribe(AddedSubtopicEvent.class, null,
								this);
					} catch (InvalidEventTypeException e) {
						e.printStackTrace();
					}
					break;
				case 2:
					console.writeLine("<topic of interest> <source>");
					String[] splitLine = console.readLine().split(" ");
					String domainName = splitLine[0];
					String source = splitLine[1];
					try {
						eventService.subscribe(ReadEvent.class,
								new ReadingFilter(domainName, source), this);
					} catch (InvalidEventTypeException e) {
						e.printStackTrace();
					}
					break;
				default:
					break;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		} while (option != 3);
		console.close();
	}

	@Override
	public void inform(Event event) {
		if (event instanceof ReadEvent) {
			ReadEvent readEvent = (ReadEvent) event;
			console.writeLine(readEvent.getMessage());
			News news = readEvent.getNews();
			news.incrementViews();
			eventService.publish(new AckEvent(news, readEvent.getSource()));
			return;
		}
		if (event instanceof AddedSubtopicEvent) {
			console.writeLine("The list of domains was modified:");
			console.writeLine(getDomains());
		}
	}
}
